package rhc.spider.util;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class AsyncTaskUtil {

	/**
	 * 线程池
	 */
	private static final ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); 
	
	/**
	 * 默认线程数
	 */
	private static final int DEFAULT_THREAD=5;
	
	/**
	 * 默认信号
	 */
	private static final Semaphore DEFAULT_SEMAPHORE=new Semaphore(DEFAULT_THREAD);
	
	
	/**放入一个线程里运行，使用默认信号
	 * @param runnable
	 */
	public static void asyncTask(Runnable runnable){
		
		runRunnable(DEFAULT_SEMAPHORE,runnable,null);
		
	}
	
	/**
	 * @param semaphore
	 * @param runnable
	 * @param latch
	 */
	public static void runRunnable(final Semaphore semaphore,final Runnable runnable,final CountDownLatch latch){
		
		NullUtil.isNull(runnable, true);
		
		if(null != semaphore){
			try {
				acquireSemaphore(semaphore,1);
			} catch (InterruptedException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
				return;
			}
		}
		
		cachedThreadPool.execute(new Runnable(){

			@Override
			public void run() {
				try{
					runnable.run();
				}catch(Exception e){
					e.printStackTrace();
				}finally{
					releaseSemaphore(semaphore,1);
					if(null != latch){
						latch.countDown();
					}
				}
			}
			
		});
		
	}
	
	/**
	 * @param count
	 * @return
	 */
	public static CountDownLatch getCountDownLatch(int count){
		return new CountDownLatch(count);
	}
	
	private static void acquireSemaphore(Semaphore semaphore,int count) throws InterruptedException{
		semaphore.acquire(count);
	}
	
	private static void releaseSemaphore(Semaphore semaphore,int count){
		semaphore.release(count);
	}
}
